# IIS权限修复脚本
# 解决HTTP 500.19错误

param(
    [string]$SitePath = "SqlsugarService.API\bin\Release\net6.0\publish",
    [switch]$CreateAppPool = $false
)

Write-Host "=== IIS权限修复脚本 ===" -ForegroundColor Green

# 检查是否以管理员身份运行
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "❌ 请以管理员身份运行此脚本" -ForegroundColor Red
    Write-Host "右键点击PowerShell，选择'以管理员身份运行'" -ForegroundColor Yellow
    exit 1
}

Write-Host "✅ 管理员权限确认" -ForegroundColor Green

# 1. 检查ASP.NET Core Hosting Bundle
Write-Host "`n1. 检查ASP.NET Core Hosting Bundle..." -ForegroundColor Yellow
$hostingBundle = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | 
    Where-Object { $_.DisplayName -like "*ASP.NET Core*Hosting Bundle*" }

if ($hostingBundle) {
    Write-Host "✅ ASP.NET Core Hosting Bundle 已安装: $($hostingBundle.DisplayName)" -ForegroundColor Green
} else {
    Write-Host "❌ ASP.NET Core Hosting Bundle 未安装" -ForegroundColor Red
    Write-Host "请下载并安装: https://dotnet.microsoft.com/download/dotnet/6.0" -ForegroundColor Yellow
    Write-Host "安装后需要重启IIS: iisreset" -ForegroundColor Yellow
}

# 2. 检查IIS功能
Write-Host "`n2. 检查IIS功能..." -ForegroundColor Yellow
$iisFeatures = @(
    "IIS-WebServerRole",
    "IIS-WebServer",
    "IIS-CommonHttpFeatures",
    "IIS-HttpErrors",
    "IIS-HttpLogging",
    "IIS-RequestFiltering",
    "IIS-StaticContent",
    "IIS-DefaultDocument",
    "IIS-DirectoryBrowsing",
    "IIS-ASPNET45"
)

foreach ($feature in $iisFeatures) {
    $featureState = Get-WindowsOptionalFeature -Online -FeatureName $feature -ErrorAction SilentlyContinue
    if ($featureState -and $featureState.State -eq "Enabled") {
        Write-Host "✅ $feature 已启用" -ForegroundColor Green
    } else {
        Write-Host "⚠️ $feature 未启用" -ForegroundColor Yellow
    }
}

# 3. 设置目录权限
Write-Host "`n3. 设置目录权限..." -ForegroundColor Yellow
$fullPath = Resolve-Path $SitePath -ErrorAction SilentlyContinue
if (-not $fullPath) {
    Write-Host "❌ 路径不存在: $SitePath" -ForegroundColor Red
    Write-Host "请先发布项目: dotnet publish --configuration Release" -ForegroundColor Yellow
    exit 1
}

Write-Host "设置路径: $fullPath" -ForegroundColor Gray

try {
    # 获取当前ACL
    $acl = Get-Acl $fullPath
    
    # 添加IIS_IUSRS权限
    $iisUsersRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
        "IIS_IUSRS", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
    $acl.SetAccessRule($iisUsersRule)
    
    # 添加IUSR权限
    $iusrRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
        "IUSR", "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow")
    $acl.SetAccessRule($iusrRule)
    
    # 添加应用程序池标识权限
    $appPoolRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
        "IIS AppPool\DefaultAppPool", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
    $acl.SetAccessRule($appPoolRule)
    
    # 应用权限
    Set-Acl -Path $fullPath -AclObject $acl
    Write-Host "✅ 权限设置完成" -ForegroundColor Green
    
} catch {
    Write-Host "❌ 权限设置失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 4. 检查web.config文件
Write-Host "`n4. 检查web.config文件..." -ForegroundColor Yellow
$webConfigPath = Join-Path $fullPath "web.config"
if (Test-Path $webConfigPath) {
    Write-Host "✅ web.config 文件存在" -ForegroundColor Green
    
    # 验证web.config内容
    try {
        [xml]$webConfig = Get-Content $webConfigPath
        $aspNetCore = $webConfig.configuration.location.'system.webServer'.aspNetCore
        if ($aspNetCore) {
            Write-Host "✅ web.config 配置正确" -ForegroundColor Green
            Write-Host "   进程路径: $($aspNetCore.processPath)" -ForegroundColor Gray
            Write-Host "   参数: $($aspNetCore.arguments)" -ForegroundColor Gray
        } else {
            Write-Host "⚠️ web.config 缺少aspNetCore配置" -ForegroundColor Yellow
        }
    } catch {
        Write-Host "❌ web.config 格式错误: $($_.Exception.Message)" -ForegroundColor Red
    }
} else {
    Write-Host "❌ web.config 文件不存在" -ForegroundColor Red
}

# 5. 创建应用程序池（可选）
if ($CreateAppPool) {
    Write-Host "`n5. 创建应用程序池..." -ForegroundColor Yellow
    try {
        Import-Module WebAdministration -ErrorAction Stop
        
        $appPoolName = "SqlsugarService"
        if (Get-IISAppPool -Name $appPoolName -ErrorAction SilentlyContinue) {
            Write-Host "应用程序池 '$appPoolName' 已存在" -ForegroundColor Yellow
        } else {
            New-WebAppPool -Name $appPoolName
            Set-ItemProperty -Path "IIS:\AppPools\$appPoolName" -Name "managedRuntimeVersion" -Value ""
            Set-ItemProperty -Path "IIS:\AppPools\$appPoolName" -Name "processModel.identityType" -Value "ApplicationPoolIdentity"
            Write-Host "✅ 应用程序池 '$appPoolName' 创建成功" -ForegroundColor Green
        }
    } catch {
        Write-Host "❌ 创建应用程序池失败: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 6. 重启IIS
Write-Host "`n6. 重启IIS..." -ForegroundColor Yellow
try {
    iisreset
    Write-Host "✅ IIS重启完成" -ForegroundColor Green
} catch {
    Write-Host "❌ IIS重启失败: $($_.Exception.Message)" -ForegroundColor Red
}

Write-Host "`n=== 修复完成 ===" -ForegroundColor Green
Write-Host "如果问题仍然存在，请检查:" -ForegroundColor Yellow
Write-Host "1. ASP.NET Core Hosting Bundle 是否正确安装" -ForegroundColor White
Write-Host "2. 应用程序池 .NET CLR 版本是否设置为'无托管代码'" -ForegroundColor White
Write-Host "3. 网站绑定和物理路径是否正确" -ForegroundColor White
Write-Host "4. Windows事件日志中的详细错误信息" -ForegroundColor White
